package com.cocotingo.snail.template.models;

import java.util.HashMap;
import java.util.Map;

import com.cocotingo.snail.template.TemplateSyntaxException;

public class HandlerNode extends Node {
	
	private final Map<String, String> handlers;
	
	public HandlerNode() {
		handlers = new HashMap<String, String>();
	}
	
	public void addHandler(String eventName, String handlerName) {
		handlers.put(eventName, handlerName);
	}
	
	public void removeHandler(String eventName) {
		handlers.remove(eventName);
	}
	
	public Iterable<String> eventNames() {
		return handlers.keySet();
	}
	
	public String getHandlerName(String eventName) {
		return handlers.get(eventName);
	}
	
	@Override
	public void validateNode() throws TemplateSyntaxException {
		for (String eventName : handlers.keySet()) {
			String handlerName = handlers.get(eventName);
			if (eventName == null || eventName.isEmpty()) throw new TemplateSyntaxException(this, "HandlerNode.eventName shouldn't be empty/null.");
			if (handlerName == null || handlerName.isEmpty()) throw new TemplateSyntaxException(this, "HandlerNode.handlerName shouldn't be empty/null.");
		}
	}

	@Override
	public Iterable<Node> children() {
		return Node.EMPTY_ITERABLE;
	}

	@Override
	protected String getXMLNodeName() {
		return "Handler";
	}

	@Override
	protected String getXMLAttributes() {
		StringBuffer buf = new StringBuffer();
		for (String key : handlers.keySet()) {
			buf.append(String.format(" %s=\"%s\"", key, handlers.get(key)));
		}
		if (buf.length() > 0 && buf.charAt(0) == ' ') {
			return buf.substring(1);
		} else {
			return buf.toString();
		}
	}

}
